package com.motu.monstercity.server.game.logichandler;

import com.google.protobuf.InvalidProtocolBufferException;
import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.protocol.Common.PBMarryInfo;
import com.motu.monstercity.protocol.Common.PBUserChildCls;
import com.motu.monstercity.protocol.Common.PBUserChildUnmarried;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameChild.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.LockKey;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.skill.SkillConstant;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.system.UserExp;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.SensitivewordEngine;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.shareddata.Lock;

import java.util.ArrayList;
import java.util.List;


public class ChildHandler {
    // CMD_GAME_CHILD_INFO = 71401; //请求子嗣列表
    public static Object CMD_GAME_CHILD_INFO(RequestParam clientParam) throws Exception {
        CSGameChildInfoResponse.Builder response = CSGameChildInfoResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        long userId = clientParam.getUserId();

        UserInfo userInfo = GameUser.getUserInfo(userId);
        ChildManager.unlockClassRoom(pbUserData, userInfo);
        for (UserChildCls userChildCls : ChildManager.getUserChildClsList(userId)) {
            ProtoDataUtils.updatePBUserData(pbUserData, userChildCls, true);
        }

        //不婚主义列表
        List<UserChildAlone> list = ChildManager.getUserChildAloneList(userId);
        for (UserChildAlone userChildAlone : list) {
            ProtoDataUtils.updatePBUserData(pbUserData, userChildAlone, true);
        }

        //未婚列表
        List<UserChildUnmarried> list2 = ChildManager.getUserChildUnmarriedList(userId);
        for (UserChildUnmarried userChildUnmarried : list2) {
            ProtoDataUtils.updatePBUserData(pbUserData, userChildUnmarried, true);
        }

        return response;
    }

    //CMD_GAME_CHILD_CLS_INFO = 71402; //请求教室信息(0全部，1-5指定教室，现在只用0)
    public static Object CMD_GAME_CHILD_CLS_INFO(RequestParam clientParam) throws Exception {
        CSGameChildClsInfoRequest request = CSGameChildClsInfoRequest.parseFrom(clientParam.getData());
        CSGameChildClsInfoResponse.Builder response = CSGameChildClsInfoResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        long userId = clientParam.getUserId();
        int clsId = request.getId();
        //检查参数
        if (clsId < 0 || clsId > AllParam.SON_NUM_LEVEL.length) {
            return ErrorWord.BAD_PARAM;
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ChildManager.unlockClassRoom(pbUserData, userInfo);

        List<UserChildCls> list = new ArrayList<>();
        if (clsId == 0) {//根据传值获取数据(0获取全部教室数据)
            for (UserChildCls entity : ChildManager.getUserChildClsList(userId)) {
                list.add(entity);
            }
        } else {
            list.add(ChildManager.getUserChildCls(userId, clsId));
        }

        List<UserSecretary> secretaryList = SecretaryManager.getUserSecretaries(userId);// 秘书列表
        for (UserChildCls userChildCls : list) {
            PBUserChildCls.Builder sb = userChildCls.takeInitBuilder();
            if (userChildCls.getIsStudy() > 0) {
                int secrAdd = ChildManager.countStudySecrSkillAdd(userChildCls, secretaryList);
                sb.setSecrAdd(secrAdd);
            }
            pbUserData.getChildBuilder().putClsChildList(userChildCls.getClsId(), sb.build());
        }

        return response;
    }

    // CMD_GAME_CHILD_SET_NAME = 71403; // 取名
    public static Object CMD_GAME_CHILD_SET_NAME(RequestParam clientParam) throws Exception {
        CSGameChildSetNameRequest request = CSGameChildSetNameRequest.parseFrom(clientParam.getData());
        CSGameChildSetNameResponse.Builder response = CSGameChildSetNameResponse.newBuilder();
        long userId = clientParam.getUserId();
        int clsId = request.getClsId();
        String name = request.getName();
        String name2 = request.getName2();
        //验证字符串
        ErrorWord errorWord = CommonUtils.checkString(name, AllParam.SYSTEM_NAME_WORDSNUM[0], AllParam.SYSTEM_NAME_WORDSNUM[1], false);// 最小1个字符,最大7个字符
        if (errorWord != ErrorWord.SUCCESS) {
            return errorWord;
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        UserChildCls userChildCls = ChildManager.getUserChildCls(userId, clsId);
        if (userChildCls == null) {
            return ErrorWord.BAD_PARAM;
        }
        if (userChildCls.getIsStudy() == 0 || userChildCls.getStudySchedule() > 0) {// 教室里没有小孩或是开始学习就不能再改名字
            return ErrorWord.WRONG_STATUS;
        }
        //双胞胎验证第二个名字（不是双胞胎时候第二个名字没有意义所以开始不验证）
        if (userChildCls.checkIsTwins()) {
            errorWord = CommonUtils.checkString(name2, AllParam.SYSTEM_NAME_WORDSNUM[0], AllParam.SYSTEM_NAME_WORDSNUM[1], false);// 最小1个字符,最大7个字符
            if (errorWord != ErrorWord.SUCCESS) {
                return errorWord;
            }

            // 检测敏感字（先进行重名校验，在进行敏感词检测，防止重复刷文字校验api）
            String tempName2 = name2;
            try {
                name2 = SensitivewordEngine.replaceNameBySdk(name2, userExtInfo.getPlatform());
            } catch (Exception e){
                return ErrorWord.BAD_WORD;
            }
            if (!tempName2.equals(name2)) {
                return ErrorWord.BAD_WORD;// 有敏感字
            }

            userChildCls.putSisterName(name2);
        }

        // 检测敏感字（先进行重名校验，在进行敏感词检测，防止重复刷文字校验api）
        String tempName = name;
        try {
            name = SensitivewordEngine.replaceNameBySdk(name, userExtInfo.getPlatform());
        } catch (Exception e){
            return ErrorWord.BAD_WORD;
        }
        if (!tempName.equals(name)) {
            return ErrorWord.BAD_WORD;// 有敏感字
        }

        // 执行逻辑
        UserPower userPower = GameUser.getUserPower(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        userChildCls.putName(name);
        userChildCls.putBaseConsume(userPower.countCurrentEarn());
        userChildCls.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildCls);
        return response;
    }

    //CMD_GAME_CHILD_STUDY = 71404; //学习
    public static Object CMD_GAME_CHILD_STUDY(RequestParam clientParam) throws Exception {
        CSGameChildStudyRequest request = CSGameChildStudyRequest.parseFrom(clientParam.getData());
        CSGameChildStudyResponse.Builder response = CSGameChildStudyResponse.newBuilder();

        long userId = clientParam.getUserId();
        int clsId = request.getClsId();
        int num = request.getNum();
        if (num < 0 || num > 999) {
            return ErrorWord.BAD_PARAM;
        }
        boolean isOneKey = request.getType() == 2 ? true : false;

        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserAffair userAffair = GameUser.getUserAffair(userId);
        UserStage userStage = FightManager.getUserStage(userId);
        if (isOneKey && !SystemManager.checkModuleOpen(userInfo, userAffair, userStage, SystemConstant.SYSTEM_MODULE_ID_STUDY_ONEKEY))  {
            return ErrorWord.WRONG_STATUS;// 未解锁一键上课的功能
        }
        UserExp userExp = GameDataManager.getUserExp(userInfo.getLevel());
        if (userExp == null) {
            return ErrorWord.NOT_DATA;
        }

        UserChildCls userChildCls = ChildManager.getUserChildCls(userId, clsId);
        if (userChildCls == null || !userChildCls.isCanStudy()) {
            return ErrorWord.NOT_DATA_1;// 状态异常不能进行学习
        }

        long minSubNum = userChildCls.takeStudyConsume();// 最小需要多少的金币数量;
        long userItenNum = BagManager.getUserItemNum(userInfo, ItemId.GOLD);
        if (userItenNum < minSubNum) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        UserPower userPower = GameUser.getUserPower(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        int totalNum = 0;// 实际培养次数
        long addEarn = 0L;// 增加的城市收益

        int studyNum = userChildCls.countMaxStudyNum(userItenNum); // 实际可以上课的次数,最多把体力用完 D D+ 品质培训不需要消耗金币 实际可以上课的次数,最多把体力用完 D D+ 品质培训不需要消耗金币
        if (!isOneKey) {// 单次上课 客户端多次操作会固定时间再请求，避免交互量过大
            if (num == 0) {
                num = 1;
            } else if (num > studyNum) {
                num = studyNum;// 最少1次，最多把体力或是金币用完
            }
            totalNum = num;
        } else {// 一键上课,直到金币不足
            totalNum = studyNum;
        }

        userChildCls.subEnergy(userInfo, totalNum);// 扣除体力 上课一次消耗1点体力
        addEarn = userChildCls.addStudySchedule(userInfo, userExp, userChildCls.takeAddStudy() * totalNum, userChildCls.checkIsTwins());// 增加上课的进度
        RewardManager.subReward(userInfo, ItemId.GOLD, minSubNum * totalNum, pbUserData, LogType.CHILD_STUDY);
        RewardManager.addReward(userInfo, ItemId.PARTNER_EXP, ChildManager.countStudyExpNum(userId, userChildCls, userExp) * totalNum, pbUserData, LogType.CHILD_STUDY);
        userChildCls.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildCls);

        if (addEarn > 0) {// // 增量更新子嗣的总收益
            userPower.addChildEarn(pbUserData, userInfo, addEarn);
        }

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_4, totalNum);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_4, totalNum);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_134, totalNum);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_134, totalNum);
        return response;
    }

    //CMD_GAME_CHILD_GRADUATION = 71405; //毕业
    public static Object CMD_GAME_CHILD_GRADUATION(RequestParam clientParam) throws Exception {
        CSGameChildGraduationRequest request = CSGameChildGraduationRequest.parseFrom(clientParam.getData());
        CSGameChildGraduationResponse.Builder response = CSGameChildGraduationResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        long userId = clientParam.getUserId();
        int clsId = request.getId();

        //验证教室，是否存在，是否有学生，教学进度是否已满
        UserChildCls userChildCls = ChildManager.getUserChildCls(userId, clsId);
        if (userChildCls == null || userChildCls.getIsStudy() != 1 || userChildCls.getStudySchedule() < AllParam.CHILD_COURSE_MAX) {
            return ErrorWord.WRONG_STATUS;
        }
        // 验证是否未婚子嗣数量是否达到上限
        if (!ChildManager.checkUnMarryNum(userChildCls, userId)) {
            return ErrorWord.ALREADY_MAX;
        }

        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        UserExp userExp = GameDataManager.getUserExp(userInfo.getLevel());
        UserChildInfo userChildInfo = ChildManager.getUserChildInfo(userId);
        int childNum = userChildCls.countChildNum();// 子嗣数量,1或是2
        userChildInfo.addGraduationNum(pbUserData, childNum);// 增加毕业子嗣的数量

        int itemId = AllParam.CHILD_CHARACTER_REWARD[userChildCls.getCharacterId() - 1];// 子嗣性格奖励
        long rewardItemNum = ChildManager.takeGraduateRewardItemNum(userChildCls.getQuality());// 子嗣性格奖励数量
        long itemNumTotal = 0L;//子嗣性格奖励总数量

        long earnAddBase = ChildManager.countEarnAddBaseValue(userInfo, userChildCls, userExp);// 执行毕业时,此时秘书魅力会有变化 子嗣 城市收益加成的基础值
        long earnAddTotal = 0L;// 总的城市收益加成

        int aloneAdd = 0;// 孤独终老的加成
        int qualityAdd = userChildCls.takeQualityEarnAdd();// 品质加成 10000  则加成显示100%
        long diffEarnAdd = 0;// 毕业时增加的城市收益加成=总的收益-之前按进度已加的
        for (int i=0;i<childNum;i++) {
            boolean isAlone = false;
            if (userChildInfo.getIsFirstChild() == 0) {// 第一个小孩毕业必定不是不婚主义，引导用
                userChildInfo.putIsFirstChild(1);
            } else {
                isAlone =  Tool.checkRandom(AllParam.CHILD_ALONE / 100);//（1+不婚主义%【不婚主义=200%~750%】）
            }

            if (isAlone) {
                itemNumTotal += rewardItemNum * AllParam.CHILD_ALONE_REWARD_TIMES;// 孤独终老奖励给3倍
                aloneAdd = ChildManager.takeEranAddAlone();// 不婚主义的加成随机区间
                int skillAdd = SkillManager.getSkillMoudleAdd(userId, SkillConstant.EFFECT_TYPE_17, 0);// 后代单身主义收益@
                earnAddTotal = earnAddBase + earnAddBase * (aloneAdd + skillAdd) / 10000;// 不婚主义的加成随机区间
                userChildInfo.addAloneNum(1);// 增加孤独终老的子嗣数量
                MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_181, userChildInfo.getAloneNum());
            } else {
                itemNumTotal += rewardItemNum;
                earnAddTotal = earnAddBase;
            }

            diffEarnAdd += (earnAddTotal - userChildCls.getAddition());// 毕业时增加的城市收益加成=总的收益-之前按进度已加的
            userChildCls.putAddition(earnAddTotal);// 更新总的收益
            // 记录子嗣中历史最高城市收益加成的子嗣快照，并更新榜单
            ChildManager.updateRankChild(pbUserData, userInfo, userChildInfo, userChildCls, earnAddTotal);
            //用于展示的详细加成信息
            PBUserGraduationInfo.Builder pbUserGraduationInfo = ChildManager.getPbUserGraduationInfo(userChildCls, aloneAdd, qualityAdd, i);
            response.addGraduationInfoList(pbUserGraduationInfo.build());

            if (isAlone) {
                UserChildAlone userChildAlone = new UserChildAlone(userId, userChildCls);// 生成孤独终老的子嗣数据
                userChildAlone.doCreate();
                ProtoDataUtils.updatePBUserData(pbUserData, userChildAlone, true);
            } else {
                UserChildUnmarried userChildUnmarried = new UserChildUnmarried(userId, userChildCls, i);// 生成未婚的子嗣数据
                userChildUnmarried.doCreate();
                ProtoDataUtils.updatePBUserData(pbUserData, userChildUnmarried, true);
            }
        }
        RewardManager.addReward(userInfo, itemId, itemNumTotal, pbUserData, LogType.CHILD_GRADUATION);

        if (diffEarnAdd > 0) {// 毕业时还要补的城市收益加成,之前进度时有分批给了
            userPower.addChildEarn(pbUserData, userInfo, diffEarnAdd);
        }

        userChildInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildInfo);

        userChildCls.cleanChild();
        userChildCls.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildCls);

        return response;
    }

    // CMD_GAME_CHILD_CLS_GET_SKILLADD = 71413; // 获取这个教室的每次上课获得的干员经验的秘书基因加成
    public static Object CMD_GAME_CHILD_CLS_GET_SKILLADD(RequestParam clientParam) throws Exception {
        CSGameChildClsGetSkilladdRequest request = CSGameChildClsGetSkilladdRequest.parseFrom(clientParam.getData());
        CSGameChildClsGetSkilladdResponse.Builder response = CSGameChildClsGetSkilladdResponse.newBuilder();

        long userId = clientParam.getUserId();
        int clsId = request.getId();

        //验证教室，是否存在，是否有学生，教学进度是否已满
        UserChildCls userChildCls = ChildManager.getUserChildCls(userId, clsId);
        if (userChildCls == null || userChildCls.getIsStudy() != 1) {
            return ErrorWord.WRONG_STATUS;
        }

        // 执行逻辑
        List<UserSecretary> secretaryList = SecretaryManager.getUserSecretaries(userId);// 秘书技能列表
        int addValue = ChildManager.countStudySecrSkillAdd(userChildCls, secretaryList);
        response.setAddValue(addValue);

        return response;
    }

    // CMD_GAME_CHILD_LIST = 71414; // 子嗣联姻，子嗣列表，0-已毕业的未婚子嗣，1-已婚子嗣，2-不婚主义的子嗣
    public static Object CMD_GAME_CHILD_LIST(RequestParam clientParam) throws Exception {
        CSGameChildListRequest request = CSGameChildListRequest.parseFrom(clientParam.getData());
        CSGameChildListResponse.Builder response = CSGameChildListResponse.newBuilder();

        PBUserData.Builder pbUserData = response.getUserBuilder();
        long userId = clientParam.getUserId();
        int type = request.getType();
        if (type == 0) {// 0-已毕业的未婚子嗣列表
            List<UserChildUnmarried> list = ChildManager.getUserChildUnmarriedList(userId);
            for (UserChildUnmarried entity : list) {
                ProtoDataUtils.updatePBUserData(pbUserData, entity, true);
            }
        } else if (type == 1) {// 1-已婚子嗣
            List<UserChildMarry> list = ChildManager.getUserChildMarryList(userId);
            for (UserChildMarry entity : list) {
                ProtoDataUtils.updatePBUserData(pbUserData, entity, true);
            }
        } else if (type == 2) {// 2-不婚主义的子嗣
            List<UserChildAlone> list = ChildManager.getUserChildAloneList(userId);
            for (UserChildAlone entity : list) {
                ProtoDataUtils.updatePBUserData(pbUserData, entity, true);
            }
        }

        return response;
    }

    // CMD_GAME_CHILD_MARRY_PUBLISH = 71415; // 发布联姻
    public static Object CMD_GAME_CHILD_MARRY_PUBLISH(RequestParam clientParam) throws Exception {
        CSGameChildMarryPublishRequest request = CSGameChildMarryPublishRequest.parseFrom(clientParam.getData());
        CSGameChildMarryPublishResponse.Builder response = CSGameChildMarryPublishResponse.newBuilder();

        long userId = clientParam.getUserId();
        long childId = request.getDbid();
        long minEarn = request.getMinEarn();
        int type = request.getType();// 0-全服，1-指定玩家
        long userIdTarget = request.getUid();

        UserChildUnmarried userChildUnmarried = ChildManager.getUserChildUnmarried(userId, childId);
        if (userChildUnmarried == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        if (userChildUnmarried.isMarryTime()) {
            return ErrorWord.REPEATED_OPERATION;// 已经是征婚状态了
        }

        if (minEarn > userChildUnmarried.getEarnAdd()) {
            return ErrorWord.ALREADY_MAX;// 设置的对方最低收益不能超过本身的城市收益
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (type == 1) {// 0-全服，1-指定玩家
            UserInfo userInfoTarget = GameUser.getUserInfo(userIdTarget);
            if (userInfoTarget == null || userInfoTarget.getServerId() != userInfo.getServerId()) {
                return ErrorWord.ENTITY_NOT_EXIST;//  userid异常，用同服
            }
            userChildUnmarried.putMarryState((byte) 2);
            userChildUnmarried.putUserIdTarget(userIdTarget);

            UserMarryApply userMarryApply = new UserMarryApply(userIdTarget, childId, userId, userChildUnmarried.getSex());
            userMarryApply.doCreate();
        } else {
            userChildUnmarried.putMarryState((byte) 1);
            ChildManager.createServerMarry(userInfo, userChildUnmarried, minEarn);// 创建全服征婚数据
        }
        userChildUnmarried.putMarryTime(TimeUtils.getCurTime());
        userChildUnmarried.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildUnmarried);

        return response;
    }


    // CMD_GAME_CHILD_MARRY_CANCEL = 71416; // 取消联姻
    public static Object CMD_GAME_CHILD_MARRY_CANCEL(RequestParam clientParam) throws Exception {
        CSGameChildMarryCancelRequest request = CSGameChildMarryCancelRequest.parseFrom(clientParam.getData());
        CSGameChildMarryCancelResponse.Builder response = CSGameChildMarryCancelResponse.newBuilder();

        long userId = clientParam.getUserId();
        long childId = request.getDbid();

        UserChildUnmarried userChildUnmarried = ChildManager.getUserChildUnmarried(userId, childId);
        if (userChildUnmarried == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        if (!userChildUnmarried.isMarryTime()) {
            return ErrorWord.WRONG_STATUS;// 不是征婚状态
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);

        // 执行逻辑
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getMarryLock(childId));
            ChildManager.cancelMarryInfo(userInfo, userChildUnmarried, null, null);// 取消征婚，删除servermarry数据，和 榜单数据匹配池子,或联姻请求
            userChildUnmarried.putMarryState((byte) 0);
            userChildUnmarried.putMarryTime(0);
            userChildUnmarried.putUserIdTarget(0);
            userChildUnmarried.update();
        } catch (InvalidProtocolBufferException e) {
            return ErrorWord.PROTOCOL_PARSE_FAILED;
        } finally {// 释放锁
            MainService.releaseVertLock(lock);
        }

        PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildUnmarried);

        return response;
    }

    // CMD_GAME_CHILD_MARRY_INFO_REFRESH = 71418; // 刷新匹配到的联姻信息
    public static Object CMD_GAME_CHILD_MARRY_INFO_REFRESH(RequestParam clientParam) throws Exception {
        CSGameChildMarryInfoRefreshRequest request = CSGameChildMarryInfoRefreshRequest.parseFrom(clientParam.getData());
        CSGameChildMarryInfoRefreshResponse.Builder response = CSGameChildMarryInfoRefreshResponse.newBuilder();

        long userId = clientParam.getUserId();
        long childId = request.getDbid();

        UserChildUnmarried userChildUnmarried = ChildManager.getUserChildUnmarried(userId, childId);
        if (userChildUnmarried == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        if (userChildUnmarried.isMarryTime()) {
            return ErrorWord.WRONG_STATUS;// 处于征婚状态，不能刷新,要先取消征婚
        }

        if (TimeUtils.getTimeDiff(userChildUnmarried.getRefreshTime()) < AllParam.CHILD_MARRY_MATCH_REFRESH_CDTIME) {
            return ErrorWord.STILL_IN_CDTIME;//  未到cd时间
        }


        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        ChildManager.refreshMatchInfo(userInfo, userChildUnmarried);// 刷新匹配到的可联姻数据
        userChildUnmarried.putRefreshTime(TimeUtils.getCurTime());
        userChildUnmarried.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildUnmarried);

        return response;
    }


    // CMD_GAME_CHILD_MARRY_DO = 71420; // 进行联姻
    public static Object CMD_GAME_CHILD_MARRY_DO(RequestParam clientParam) throws Exception {
        CSGameChildMarryDoRequest request = CSGameChildMarryDoRequest.parseFrom(clientParam.getData());
        CSGameChildMarryDoResponse.Builder response = CSGameChildMarryDoResponse.newBuilder();

        long userId = clientParam.getUserId();
        long childId = request.getChildIdMy();
        int type = request.getType();// 0-对方是玩家，1-对方是机器人
        long userIdTarget = request.getUserIdTarget();// 对方的userid,0-机器人
        long dbidTarget = request.getDbidTarget();// 对方的childid, 或是机器人的dbid

        UserInfo userInfo = GameUser.getUserInfo(userId);
        int serverId = userInfo.getServerId();

        UserChildUnmarried userChildUnmarried = ChildManager.getUserChildUnmarried(userId, childId);
        if (userChildUnmarried == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        if (userChildUnmarried.isMarryTime()) {
            return ErrorWord.WRONG_STATUS;// 处于征婚状态，不能联姻，要先取消征婚
        }

        int characterId = 0;// 对方的性格
        long uid = 0L;
        String name = "";
        int quality = 0;// 对方的品质
        long earnAdd = 0L;// 增加的城市收益
        int career = 0;
        int partnerId = 0;
        int secretaryId = 0;
        int appearance = 0;
        if (type == 0) {// 跟玩家联姻
            UserChildUnmarried userChildUnmarriedTarget = null;
            ServerMarryInfo serverMarryInfo = null;
            Lock lock = null;
            try {
                lock = MainService.getVertLock(LockKey.getMarryLock(dbidTarget));
                userChildUnmarriedTarget = ChildManager.getUserChildUnmarried(userIdTarget, dbidTarget);
                if (userChildUnmarriedTarget == null || !userChildUnmarriedTarget.isMarryTime()) {
                    return ErrorWord.ENTITY_NOT_EXIST;
                }
                if (userChildUnmarriedTarget.isMarryServer()) {// 对方是全服联姻
                    serverMarryInfo = ChildManager.getServerMarryInfo(serverId, dbidTarget);
                    if (serverMarryInfo == null || serverMarryInfo.getUserId() == userId || serverMarryInfo.getSex() == userChildUnmarried.getSex()) {
                        return ErrorWord.ENTITY_NOT_EXIST;// 结婚对象不存在,自己不能跟自己结婚，同性不能结婚
                    }
                    if (userChildUnmarried.getEarnAdd() < serverMarryInfo.getMinEarnAdd()) {
                        return ErrorWord.ITEM_LACK;// 城市收益没达到对方的要求
                    }
                } else if (userChildUnmarriedTarget.isMarryUser()) {
                    if (userChildUnmarriedTarget.getUserIdTarget() != userId) {
                        return ErrorWord.WRONG_STATUS;// 对方的联姻对象不是我
                    }
                }
                characterId = userChildUnmarriedTarget.getCharacterId();// 取对方的
                uid = userChildUnmarriedTarget.getUserId();
                name = userChildUnmarriedTarget.getName();
                quality = userChildUnmarriedTarget.getQuality();
                earnAdd = userChildUnmarriedTarget.getEarnAdd();
                career = userChildUnmarriedTarget.getCareer();
                partnerId = userChildUnmarriedTarget.getPartner();
                secretaryId = userChildUnmarriedTarget.getSecretary();
                appearance = userChildUnmarriedTarget.getAppearance();

                // 跟玩家联姻 联姻成功，处理对方的数据，发放奖励, 生成已婚子嗣数据等
                ChildManager.handleMarryTarget(userInfo, userChildUnmarried, uid, userChildUnmarriedTarget, serverMarryInfo);
            } catch (InvalidProtocolBufferException e) {
                return ErrorWord.PROTOCOL_PARSE_FAILED;
            } finally {// 释放锁
                MainService.releaseVertLock(lock);
            }
        } else {// 跟机器人联姻
            UserMarryRobot userMarryRobot = ChildManager.getUserMarryRobot(childId, dbidTarget);
            if (userMarryRobot == null) {
                return ErrorWord.ENTITY_NOT_EXIST;// 机器人不存在
            }
            characterId = userChildUnmarried.getCharacterId();// 跟机器人联姻，取我的
            name = request.getName();
            quality = userChildUnmarried.getQuality();
            earnAdd = userMarryRobot.getEarnAdd();
            career = request.getCareer();
            partnerId = request.getPartner();
            secretaryId = request.getSecretary();
            appearance = request.getAppearance();
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();

        // 联姻成功，处理我方的数据，发放奖励, 生成已婚子嗣数据等
        ChildManager.handleMarryMy(pbUserData, userInfo, userChildUnmarried, uid, name, quality, characterId, career, partnerId, secretaryId, appearance, earnAdd);
        // 更新限时任务进度
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_118, 1);// 更新主线任务,成就,日常任务的进度
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_5, 1);// 后代联姻{0}次
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_5, 1);

        return response;
    }

    // CMD_GAME_CHILD_MARRY_APPLY_LIST = 71419; // 显示别人发给我的指定联姻信息列表
    public static Object CMD_GAME_CHILD_MARRY_APPLY_LIST(RequestParam clientParam) throws Exception {
        CSGameChildMarryApplyListRequest request = CSGameChildMarryApplyListRequest.parseFrom(clientParam.getData());
        CSGameChildMarryApplyListResponse.Builder response = CSGameChildMarryApplyListResponse.newBuilder();

        long userId = clientParam.getUserId();

        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        List<UserMarryApply> list = ChildManager.getUserMarryApplyList(userId);
        for (UserMarryApply userMarryApply : list) {
            if (userMarryApply.isMarryTime()) {
                UserInfo userInfoTarget = GameUser.getUserInfo(userMarryApply.getUserIdFrom());
                UserChildUnmarried userChildUnmarriedTarget = ChildManager.getUserChildUnmarried(userMarryApply.getUserIdFrom(), userMarryApply.getChildIdFrom());
                PBMarryInfo.Builder builder = ChildManager.takePBMarryInfo(userInfoTarget, userChildUnmarriedTarget);
                pbUserData.getChildBuilder().putApplyList(userMarryApply.getId(), builder.build());
            } else {
                ChildManager.deleteMarryApply(userMarryApply);// // 删除联姻请求
            }
        }

        return response;
    }

    // CMD_GAME_CHILD_MARRY_APPLY_SET = 71421; // 设置是否接收联姻请求
    public static Object CMD_GAME_CHILD_MARRY_APPLY_SET(RequestParam clientParam) throws Exception {
        CSGameChildMarryApplySetRequest request = CSGameChildMarryApplySetRequest.parseFrom(clientParam.getData());
        CSGameChildMarryApplySetResponse.Builder response = CSGameChildMarryApplySetResponse.newBuilder();

        long userId = clientParam.getUserId();
        boolean isRefuse = request.getIsRefuse();

        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserChildInfo userChildInfo = ChildManager.getUserChildInfo(userId);
        userChildInfo.putIsRefuseMarryApply(isRefuse ? 1 : 0);
        userChildInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildInfo);

        return response;
    }

    // CMD_GAME_CHILD_MARRY_APPLY_REFUSE = 71422; // 拒绝联姻请求
    public static Object CMD_GAME_CHILD_MARRY_APPLY_REFUSE(RequestParam clientParam) throws Exception {
        CSGameChildMarryApplyRefuseRequest request = CSGameChildMarryApplyRefuseRequest.parseFrom(clientParam.getData());
        CSGameChildMarryApplyRefuseResponse.Builder response = CSGameChildMarryApplyRefuseResponse.newBuilder();

        long userId = clientParam.getUserId();
        boolean isAll = request.getIsAll();
        long childIdFrom = request.getChildIdFrom();

        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        List<UserMarryApply> list = new ArrayList<>();
        if (isAll) {
            list = ChildManager.getUserMarryApplyList(userId);
        } else {
            list.add(ChildManager.getUserMarryApply(userId, childIdFrom));
        }

        for (UserMarryApply userMarryApply : list) {
            pbUserData.getChildBuilder().putApplyList(userMarryApply.getId(), PBMarryInfo.getDefaultInstance());
            ChildManager.deleteMarryApply(userMarryApply);// // 删除联姻请求
        }

        return response;
    }

    // CMD_GAME_CHILD_MARRY_INFO_LIST_USERID = 71423; // 根据userid 查看对方发布的联姻信息列表
    public static Object CMD_GAME_CHILD_MARRY_INFO_LIST_USERID(RequestParam clientParam) throws Exception {
        CSGameChildMarryInfoListUseridRequest request = CSGameChildMarryInfoListUseridRequest.parseFrom(clientParam.getData());
        CSGameChildMarryInfoListUseridResponse.Builder response = CSGameChildMarryInfoListUseridResponse.newBuilder();

        long userId = clientParam.getUserId();
        long userIdTarget = request.getUserIdTarget();

        // 执行逻辑
        UserInfo userInfoTarget = GameUser.getUserInfo(userIdTarget);
        if (userInfoTarget != null) {
            List<ServerMarryInfo> list = ChildManager.getServerMarryInfoList(userInfoTarget.getServerId());
            for (ServerMarryInfo serverMarryInfo : list) {
                if (serverMarryInfo.getUserId() == userIdTarget) {
                    long childId = serverMarryInfo.getChildId();
                    UserChildUnmarried userChildUnmarried = ChildManager.getUserChildUnmarried(userIdTarget, childId);
                    PBMarryInfo.Builder builder = ChildManager.takePBMarryInfo(userInfoTarget, userChildUnmarried);
                    response.putMarryInfo(childId, builder.build());
                }
            }
        }

        return response;
    }

    // CMD_GAME_CHILD_UNMARRYIED_LIST_USERID = 71424; // 根据userid 查看对方所有的未婚子嗣列表
    public static Object CMD_GAME_CHILD_UNMARRYIED_LIST_USERID(RequestParam clientParam) throws Exception {
        CSGameChildUnmarryiedListUseridRequest request = CSGameChildUnmarryiedListUseridRequest.parseFrom(clientParam.getData());
        CSGameChildUnmarryiedListUseridResponse.Builder response = CSGameChildUnmarryiedListUseridResponse.newBuilder();

        long userId = clientParam.getUserId();
        long userIdTarget = request.getUserIdTarget();

        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserInfo userInfoTarget = GameUser.getUserInfo(userIdTarget);

        if (userInfo == null || userInfoTarget == null || userInfo.getServerId() != userInfoTarget.getServerId()) {
            return ErrorWord.NOT_DATA;//  没有该玩家数据，或者不是同个服务器
        }

        List<UserChildUnmarried> list = ChildManager.getUserChildUnmarriedList(userIdTarget);
        for (UserChildUnmarried userChildUnmarried : list) {
            PBUserChildUnmarried.Builder builder = userChildUnmarried.takeInitBuilder();
            response.putChildList(userChildUnmarried.getId(), builder.build());
        }

        return response;
    }

}
